<?php
/**
 * XmuSlh, web platform of Student Association Federation of Xiamen University
 * 
 * Rewritting one or some pages of StatusNet. 
 * To get the original version, please visit <http://status.net/>.
 * 
 * StatusNet, the distributed open-source microblogging tool
 * 
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * The PhotoSet class for table 'photoset'.
 * 
 * @author		ytukie <ytukie@gmail.com>
 * @version		0.2
 * 
 * 0.2)  Adjusts the 'delete' function, add deletion of photo news.
 * 		 Adds the the 'getPhotonews' function.
 * 0.3)  Adds the 'getTopNPhotoIds' function.
 */

// XmuSlh only.
if ( !defined('XMUSLH')) { exit(1); }

// Requirements.
require_once INSTALLDIR . '/lib/slh_util.php';

require_once INSTALLDIR . '/classes/Memcached_DataObject.php';

// Definitions.
// Column of status reserves.

class PhotoSet extends Memcached_DataObject
{
	public $__table = 'photoset';			// table name
	public $id;								// int(11)  primary_key not_null
	public $user_id;						// int(11)  foreign_key not_null
	public $title;							// varchar(255)
	public $message;						// varchar(255)
	public $photocnt;						// int(11)
	public $created;						// datetime()  not_null
	
	// Static get
	function staticGet($key, $value = null)
	{
		return Memcached_DataObject::staticGet('PhotoSet', $key, $value); 
	}
	
	/**
	 * Get the related photos of this photo set.
	 * 
	 * @return object, Photo
	 */
	function getPhotos()
	{
		$photos = new Photo();
		
		$photos->whereAdd('photoset_id = ' . $this->id);
		$photos->orderBy('created DESC');
		
		if ($photos->find()) {
			return $photos;
		} else {
			return null;
		}
	}
	
	/**
	 * Get the related photo news of this photo set.
	 * 
	 * @return object, PhotoNews
	 */
	function getPhotonews()
	{
		$photonews = new PhotoNews();
		
		$photonews->photoset_id = $this->id;
		
		if ($photonews->find()) {
			return $photonews;
		} else {
			return null;
		}
	}
	
	/**
	 * To get the latest photos ids.
	 * Default to get 3.
	 */
	function getTopNPhotoIds($n = 4)
	{
		$photos = new Photo();
		
		$photos->selectAdd();
		$photos->selectAdd('id, photoset_id');
		$photos->whereAdd('photoset_id = ' . $this->id);
		$photos->orderBy('created DESC');
		$photos->limit(0, $n);
	
		$photoids = array();
		if ($photos->find()) {
			while ($photos->fetch() && ($n-- > 0)) {
				$photoids[] = $photos->id;
			}
		}
		
		return $photoids;
	}
	
	/**
	 * Delete the photo set with its relative photos.
	 * Both in database and filesystem.
	 * 
	 * And the 
	 */
	function delete()
	{
		// Delete the photos.
		$photos = $this->getPhotos();
		if ( !is_null($photos)) {
			while ($photos->fetch()) {
				$photos->delete();
			}
		}
		
		// Delete the photo news.
		$photonews = $this->getPhotonews();
		if ( !is_null($photonews)) {
			while ($photonews->fetch()) {
				$photonews->delete();
			}
		}
				
		parent::delete();
	}
	
	/**
	 * Update the photo count of the photo set.
	 * According to the count of the 'photo'.'photoset_id'.
	 */
	function updatePhotoCount()
	{
		$query = 'SELECT `photoset_id` FROM `photo` WHERE `photoset_id` = ' . $this->id;
		$photoset = new PhotoSet();
		$photoset->query($query);
		$count = $photoset->N;
		
		// Set the count.
		$this->photocnt = $count;
		
		return $this->update();
	}
	
	/**
	 * Get the fresh N photo ids.
	 * 
	 * @param $photoset_id,
	 * @param $n, the top N photos.
	 * @return array().
	 */
	static function getFreshPhotoIds($photoset_id, $n)
	{
		$photo = new Photo();
		
		$photo->selectAdd();
		$photo->selectAdd('id');
		$photo->whereAdd('photoset_id = ' . $photoset_id );
		$photo->orderBy('created DESC');
		$photo->limit(0, $n);
		
		$ids = array();
		if ($photo->find()) {
			while ($photo->fetch()) {
				$ids[] = $photo->id;
			}
		}
		
		$photo->free();
		$photo = NULL;
		
		$photo_ids = array();
		for ($i = 0; $i < $n; ++$i) {
			if (isset($ids[$i])) {
				$photo_ids[$i] = $ids[$i];
			} else {
				$photo_ids[$i] = 0;
			}
		}
		
		return $photo_ids;
	}
	
	/**
	 * Check if 'photoset'.'id' exists.
	 */
	static function hasId($id)
	{
		$query = 'SELECT `id` FROM `photoset` WHERE `id` = ' . $id;

		$photoset = new PhotoSet();
		$photoset->query($query);
		
		if ($photoset->fetch()) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * Add a photoset into the database.
	 */
	static function add($fields)
	{
		// Magically put fields into current scope.
		extract($fields);
		
		$photoset = new PhotoSet();
		$photoset->user_id = $user_id;
		$photoset->title = $title;
		$photoset->message = $message;
		$photoset->created = slh_sql_now();
		
		$photoset_id = $photoset->insert();
		if (empty($photoset_id)) {
			slh_log_db_error($photoset, 'INSERT', __FILE__);
			return false;
		}
		
		return $photoset_id;
	} 
	
	/**
	 * Get the ids as a list. Use offset and limit to control
	 * the pagination.
	 * 
	 * @param user_id, the id of the photoset owner, 0 = slh, other = association.
	 */
	static function getIdsByUserRelationList($user_id,
											 $offset = 0,
								 			 $limit = 0)
	{
		$photoset = new PhotoSet();
		
		$photoset->selectAdd();
		$photoset->selectAdd('id');
		$photoset->whereAdd('user_id = ' . $user_id );
		
		$photoset->orderBy('created DESC');
		
		if ( !is_null($offset)) {
			$photoset->limit($offset, $limit);
		}
		
		$ids = array();
		if ($photoset->find()) {
			while ($photoset->fetch()) {
				$ids[] = $photoset->id;
			}
		}
		
		$photoset->free();
		$photoset = NULL;
		
		return $ids;
	}
	
	/**
	 * Get the special ids of the photo sets.
	 * 
	 * Usually the list with pagination.
	 */
	function getPhotosetsByIds($ids)
	{
		$cache = Cache::instance();
		
		if ( !empty($cache)) {
			$photosets = array();
			foreach ($ids as $id) {
				$p = PhotoSet::staticGet('id', $id);
				if ( !empty($p)) {
					$photosets[] = $p;
				}
			}
			
			return new ArrayWrapper($photosets);
		} else {
			// Miss the cache.
			$photosets = new PhotoSet();
			if (empty($ids)) {
				return $photosets;
			}
			
			$photosets->whereAdd('id in (' . implode(', ', $ids) . ')');
			$photosets->find();
			
			$temp = array();
			while ($photosets->fetch()) {
				$temp[$photosets->id] = clone($photosets);
			}
			
			$wrapped = array();
			
			foreach($ids as $id) {
				if (array_key_exists($id, $temp)) {
					$wrapped[] = $temp[$id];
				}
			}
			
			return new ArrayWrapper($wrapped);
		}
	}
}
?>